package com.ms.orm.conditions.segments;

import com.ms.orm.conditions.ISqlSegment;
import com.ms.orm.constants.StringPool;
import lombok.AccessLevel;
import lombok.Getter;

import java.util.Arrays;
import java.util.List;

/**
 * 合并 SQL 片段
 * Copy from mybatis-plus
 * @author .
 */
@Getter
@SuppressWarnings("serial")
public class MergeSegments implements ISqlSegment {

    /**
     * 1、普通的SQL片段，where 还是后面的？
     * @param
     */
    private final NormalSegmentList normal = new NormalSegmentList();

    /**
     * 2、group by 片段
     * @param
     */
    private final GroupBySegmentList groupBy = new GroupBySegmentList();
    /**
     * 3、having 片段
     * @param
     */
    private final HavingSegmentList having = new HavingSegmentList();
    /**
     * order by 片段
     */
    private final OrderBySegmentList orderBy = new OrderBySegmentList();

    @Getter(AccessLevel.NONE)
    private String sqlSegment = StringPool.EMPTY;
    @Getter(AccessLevel.NONE)
    private boolean cacheSqlSegment = true;

    /**
     * 添加sql片段
     * @param iSqlSegments
     */
    public void add(ISqlSegment... iSqlSegments) {
        List<ISqlSegment> list = Arrays.asList(iSqlSegments);
        ISqlSegment firstSqlSegment = list.get(0);
        if (MatchSegment.ORDER_BY.match(firstSqlSegment)) {
            orderBy.addAll(list);
        } else if (MatchSegment.GROUP_BY.match(firstSqlSegment)) {
            groupBy.addAll(list);
        } else if (MatchSegment.HAVING.match(firstSqlSegment)) {
            having.addAll(list);
        } else {
            normal.addAll(list);
        }
        cacheSqlSegment = false;
    }

    /**
     * 合并得到 完整的查询SQL
     * @return
     */
    @Override
    public String getSqlSegment() {
        if (cacheSqlSegment) {
            return sqlSegment;
        }
        cacheSqlSegment = true;
        if (normal.isEmpty()) {
            if (!groupBy.isEmpty() || !orderBy.isEmpty()) {
                sqlSegment = groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
            }
        } else {
            sqlSegment = normal.getSqlSegment() + groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
        }
        return sqlSegment;
    }

    /**
     * 清理
     *
     * @since 3.3.1
     */
    public void clear() {
        sqlSegment = StringPool.EMPTY;
        cacheSqlSegment = true;
        normal.clear();
        groupBy.clear();
        having.clear();
        orderBy.clear();
    }
}
